package com.example.kotlin

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.preferencesKey
import androidx.datastore.preferences.createDataStore
import androidx.lifecycle.lifecycleScope
import com.example.kotlin.utils.GenerateString
import com.example.kotlin.utils.dataStoreRead
import com.example.kotlin.utils.dataStoreSave
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class MainStoreActivity : AppCompatActivity() {

    private val name: String = GenerateString.getRandomString(5)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_store)
        initStore()
    }

    private fun initStore() {
        lifecycleScope.launch {
            dataStoreSave("mee", GenerateString.getRandomString(5))
        }

        lifecycleScope.launch {
            Log.d("taggg", dataStoreRead<String>("mee"))
        }

    }


    fun other() {
        val dataStore: DataStore<Preferences> = createDataStore(
            name = "user"
        )

        val NAME = preferencesKey<String>("username")
        runBlocking {
            dataStore.edit {
                it[NAME] = name
            }
        }

        runBlocking {
            val getName = dataStore.data
                .map {
                    it[NAME]
                }

            getName.collect {
                Log.d("taggg", it.toString())
            }
        }

        lifecycleScope.launch {
            dataStoreSave("me", name)
        }

    }
}